<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { SendMessageRequestData } from '@/api/operation/types/operation'
import { SendMessage } from '@/api/operation'
import { getToken } from '@/utils/cache/cookies'

const dialogVisible = ref<boolean>(false)
const form = reactive<SendMessageRequestData>({
  phone: '',
  type: '',
  content: ''
})
const formRef = ref<FormInstance | null>(null)
const rules = reactive<FormRules>({
  phone: [
    {
      required: true,
      message: '请输入用户手机号',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择消息类型',
      trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      message: '请输入消息内容',
      trigger: 'blur'
    }
  ]
})
const reset = () => {
  dialogVisible.value = false
}
const handleClose = () => {
  formRef.value?.resetFields()
}
const submit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      SendMessage({
        token: getToken() ?? '',
        ...form
      })
        .then((res) => {
          if (res.statusCode === '0') {
            dialogVisible.value = false
            ElMessage.success(res.data)
          } else {
            formRef.value?.resetFields()
          }
        })
        .catch((error) => {
          console.error(error)
        })
    }
  })
}
const open = () => {
  dialogVisible.value = true
}
defineExpose({ open })
</script>

<template>
  <el-dialog title="发送消息" v-model="dialogVisible" width="500px" @close="handleClose">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item prop="phone" label="用户手机号:">
        <el-input v-model="form.phone" placeholder="请输入用户手机号" />
      </el-form-item>
      <el-form-item prop="type" label="消息类型:">
        <el-select v-model="form.type" style="width: 100%">
          <el-option label="通知" value="通知" />
          <el-option label="活动" value="活动" />
          <el-option label="运营" value="运营" />
        </el-select>
      </el-form-item>
      <el-form-item prop="content" label="消息内容">
        <el-input
          v-model="form.content"
          placeholder="请输入消息内容"
          style="width: 100%"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button plain @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">发送</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
